<template>
  <section class="pay_content">
    <el-page-header @back="goBack" content="收费"></el-page-header>
    <div class="main_left">
      <div class="pay_left">
        <div class="pay_left_item">
          订单号：
          <br />
          {{orderCode}}
        </div>
        <!-- <div class="pay_left_item">
          门诊号：
          <br />542880000026
        </div>-->
        <div class="pay_left_item pay_left_mb">
          应收金额：
          <br />
          <span class="pay_total">￥{{totalMoney}}</span>
          <!-- <br />{{total | moneyToUpper}} -->
        </div>
        <div class="pay_left_item">
          患者姓名：
          <br />
          {{detail.name}}
        </div>
        <div class="pay_left_item">
          就诊日期：
          <br />
          {{gmtCreate}}
        </div>
        <div v-if="!isSource" class="pay_left_item">
          <span style="cursor: pointer;" @click="getDetail()">查看收费明细 ></span>
        </div>
      </div>
    </div>
    <div class="main_right">
      <div class="main_right_c">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="140px"
          @submit.native.prevent="onSubmit"
        >
          <el-form-item label="支付类型：">
            <el-checkbox-group
              @change="changeCheck"
              style="margin-bottom:20px;display:inline-block;"
              v-model="form.source"
            >
              <!-- <el-checkbox :disabled="!qxBtns.gz" :label="2" name="type">挂账金额</el-checkbox> -->
              <!-- <el-checkbox :disabled="!qxBtns.kq" :label="4" name="type">使用卡券</el-checkbox> -->
              <el-checkbox :disabled="!qxBtns.ye" :label="6" name="type">余额支付</el-checkbox>
              <!-- <el-checkbox :disabled="!qxBtns.jf" :label="5" name="type">积分抵扣</el-checkbox> -->
            </el-checkbox-group>
            <el-form-item v-for="(item,index) in sourceItem" style="width:460px;" :key="index">
              <el-input @blur="derate(item)" :disabled="isChecked" v-model="item.payMoney">
                <template slot="prepend">{{item.name}}</template>
                <template slot="append">元</template>
              </el-input>
              <label
                v-if="item.source==6"
                style="text-align:left;color:#9B9B9B;"
              >卡内余额：￥ {{detail.patientMoney}}</label>
              <label v-if="item.source==5" style="text-align:left;color:#9B9B9B;">
                总积分：{{detail.patientScore}} （单次上限{{jfUse.mostNum}}积分）
                温馨提示：积分抵扣会自动计算抵扣金额~
              </label>
            </el-form-item>

            <!-- <div v-if="show1">
              <br>
              <el-input placeholder="请输入内容" v-model="form.guazhang" style="width:450px;">
                <template slot="prepend">挂账金额</template>
              </el-input>
            </div>
            <div v-if="show2">
              <br>
              <el-input placeholder="请输入内容" v-model="form.kaquan" style="width:450px;">
                <template slot="prepend">使用卡券</template>
              </el-input>
            </div>
            <div v-if="show3">
              <br>
              <el-input placeholder="请输入内容" v-model="form.yue" style="width:450px;">
                <template slot="prepend">余额支付</template>
              </el-input>
            </div>
            <div v-if="show4">
              <br>
              <el-input placeholder="请输入内容" v-model="form.jifen" style="width:450px;">
                <template slot="prepend">积分抵扣</template>
              </el-input>
            </div>-->
          </el-form-item>
          <el-form-item label="折扣" prop="discountNumber">
            <el-checkbox v-model="isDiscount" @change="changeDiscount" name="type"></el-checkbox>
            <el-input
              v-if="isDiscount==true"
              style="width:200px;"
              @blur="computeDiscount"
              v-model="form.discountNumber"
            > <template slot="append">折</template></el-input>
          </el-form-item>
          <el-form-item label="是否减免：">
            <el-checkbox
              :disabled="!qxBtns.jm"
              v-model="type"
              @change="onChangeJM"
              style="width:120px;"
            >是</el-checkbox>
            <div v-if="type==true" style="display:inline-block;width:100%;">
              <el-checkbox-group v-model="form.reductionType">
                <el-checkbox
                  v-for="item in paytypeList"
                  :label="item.id"
                  :key="item.id"
                  style="width:150px"
                  :value="item.id"
                >{{item.desc}}减免</el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-if="type==true">
              <el-input
                style="width:200px;"
                @blur="derate()"
                :disabled="showdiscount"
                v-model="form.reductionMoney"
              >
                <template slot="append">元</template>
              </el-input>
              <label style="margin-top:0px;width:initial;">
                （减免折扣
                <el-input v-model="form.discount" :disabled="true" class="remission_input"></el-input>%）
              </label>
            </div>
          </el-form-item>
          <el-form-item label>
            <div class="needPay">还需支付：￥{{residueMoney}}</div>
          </el-form-item>
          <!-- 7.现金 8.支付宝 9.微信 10.银行卡 -->
          <el-form-item label="支付方式：" prop="resource">
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              :disabled="!qxBtns.xinjin"
              label="7"
            >现金</el-radio>
            <!-- <el-radio v-model="form.resource" @change="changeSource" :disabled="!qxBtns.card" label="10">银行卡</el-radio> -->
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              :disabled="!qxBtns.weixin"
              label="9"
            >微信</el-radio>
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              :disabled="!qxBtns.alipay"
              label="8"
            >支付宝</el-radio>
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="18"
            >POS支付</el-radio>
            <!-- <el-radio
              v-model="form.resource"
              @change="changeSource"
              style="width:140px;"
              :disabled="!qxBtns.weixin"
              label="16"
            >POS机储蓄卡</el-radio> -->
            <!-- <el-radio
              v-model="form.resource"
              @change="changeSource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="15"
            >POS机信用卡</el-radio> -->
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="19"
            >微信小助手</el-radio> 
            <el-radio
              v-model="form.resource"
              @change="changeSource"
              :disabled="!qxBtns.small"
              label="14"
            >小程序余额支付</el-radio>
            <!-- <el-radio v-model="form.resource" @change="changeSource" :disabled="!qxBtns.small" label="14">POS支付</el-radio> -->
            <!-- <el-radio-group v-model="form.resource">
            </el-radio-group>-->
          </el-form-item>
          <el-form-item label="收费金额：" prop="payMoney">
            <el-input
              v-if="form.resource!=14"
              v-model="form.payMoney"
              disabled
              @blur="getMoney"
              style="font-size:20px;width:450px;"
              placeholder="请输入收款金额"
            ></el-input>
            <el-form @submit.native.prevent="getSmallCode">
              <el-input
                v-if="form.resource==14"
                :type="textType"
                :disabled="smallDisabled"
                v-model="medicalCard"
                ref="payMoney"
                style="font-size:20px;width:450px;"
                placeholder="请扫描患者电子就诊卡二维码"
              ></el-input>
            </el-form>
            <!-- <div>
              <span class="ml20 danger">找零：￥{{balanceMoney}}元</span>
            </div>-->
          </el-form-item>
          <el-form-item v-if="form.resource==14" label="小程序验证码">
            <el-input
              v-model.number="form.code"
              style="font-size:20px;width:450px;"
              placeholder="请输入小程序付款验证码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="备注："
            prop="desc"
            :rules="type?[{
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          }]:[]"
          >
            <el-input type="textarea" v-model.trim="form.desc" style="width:450px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="btnLoading" native-type="submit">收费</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
export default {
  data() {
    return {
      type: false,
      form: {
        payMoney: "",
        xinjin: 0,
        zhifubao: 0,
        resource: "9",
        weixin: 0,
        yinhangka: 0,
        discountNumber: 1,
        reductionType: [], //减免类型
        code: "", //小程序code
        medicalCard: "",
        totalMoney: "", //总金额
        note: "", //备注
        recordNum: "", //总积分数量
        realityMoney: "", //实际金额
        orderId: "", //订单id
        discount: 0, //折扣数
        reductionMoney: 0, //减免金额
        source: [] //1医保 2挂账 3商保 4.卡券 5.积分 6.余额 7.现金 8.支付宝 9.微信 10.银行卡 11.找零 12.赠送余额  14 小程序余额支付 15 pos机信用卡 16 pos机储蓄卡 18 POS机支付  19 微信小助手
      },
      isDiscount: false,
      btnLoading: false,
      medicalCard: "",
      showdiscount: false,
      sourceItem: [],
      rules: {
        resource: [
          { required: true, message: "请选择支付方式", trigger: "change" }
        ],
        payMoney: [
          { required: true, message: "请输入收费金额", trigger: "blur" },
          { validator: validate.integerAndFloat, trigger: "blur" }
        ],
        discountNumber: [
          { required: false, message: "请输入正确的折扣", trigger: "blur" },
          { validator: validate.FloatByTwo, trigger: "blur" }
        ]
      },
      isChecked: false,
      sourName: {
        1: "医保金额",
        2: "挂账金额",
        3: "商保金额",
        4: "使用卡券",
        5: "使用积分",
        6: "余额支付",
        14: "小程序余额支付"
      },
      total: 0, //用于计算金额（变动）
      totalMoney: 0, //用于显示总金额（不变）
      detail: "",
      orderCode: "",
      show5: false,
      smallDisabled: false,
      qxBtns: {},
      paytypeList: [],
      gmtCreate: "",
      textType: "password",
      residueMoney: 0, //剩余支付
      balanceMoney: 0, //找零
      isSource: false
    };
  },
  created() {
    let th = this;
    th.getIntegralRuleById();
    th.getQX();
    th.orderCode = th.$route.query.orderCode;
    th.orderId = th.$route.query.orderId;
    let source = th.$route.query.source;
    if (source) {
      th.isSource = true;
    }
    if (th.$route.query.id) {
      th.showDetail = true;
    }
  },
  mounted() {
    this.open();
  },
  methods: {
    onChangeJM() {
      this.form.reductionMoney = 0;
      this.derate();
      this.changeDiscount();
    },
    //积分
    getIntegralRuleById() {
      let th = this;
      th.$api
        .getIntegralRuleById({ hpId: th.adminUser.hpId, type: 1 })
        .then(res => {
          if (res.executed) {
            th.jfUse = res.integralRuleList[0];
          }
        });
      th.getCommonConfigByKey("收费减免类型").then(res => {
        th.paytypeList = res;
      });
    },
    open() {
      let th = this;
      let total = 0;
      th.verifyUrlAttack(th.$route.query).then(() => {
        // th.total = th.$route.query.total;
        if (th.$route.query.patientId) {
          let uid = th.jieMi(th.$route.query.patientId);
          if (uid) {
            th.$api
              .getThePatientLibraryById({
                patientId: uid,
                hpId: th.adminUser.hpId
              })
              .then(res => {
                if (res.executed) {
                  th.detail = res.thePatientLibraryDetail;
                }
              });
          }
        }
        th.$api.getOrder({ orderId: th.$route.query.orderId }).then(res => {
          if (res.executed) {
            let list = res.dataBody.list;
            if (list) {
              for (let i = 0; i < list.length; i++) {
                total += Number(list[i].realityMoney);
              }
              th.gmtCreate = list[0].gmtCreate;
              th.total = total;
              th.residueMoney = total;
              th.totalMoney = total;
              th.form.payMoney = total;
            }
          }
        });
      });
    },
    getDetail() {
      let th = this;
      let id = "";
      if (th.isSource) {
        id = th.$route.query.orderId;
      } else {
        id = th.$route.query.id;
        th.$router.push({
          path: "/page/chargeDetail",
          query: th.getUrlToken({
            id: id,
            patientId: th.$route.query.patientId
          })
        });
      }
    },
    goBack() {
      let th = this;
      th.$router.push({
        path: "/page/chargeIndex",
        query: th.getUrlToken({
          // total: th.totalMoney,
          type: 0
        })
      });
    },
    //支付类型
    changeCheck(item) {
      let list = [];
      let th = this;
      let _item = th.sourceItem;
      for (let i = 0; i < item.length; i++) {
        let arr = {
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: 0,
          source: "",
          sourceId: "",
          remark: "",
          status: "",
          disabled: false,
          isDeleted: "",
          name: ""
        };
        arr.source = item[i];
        arr.name = th.sourName[item[i]];
        for (let j = 0; j < _item.length; j++) {
          if (_item[j].name == arr.name) {
            arr.payMoney = _item[j].payMoney;
          }
        }
        if (arr.name != "") {
          list.push(arr);
        }
      }

      th.sourceItem = list;
      th.derate();
    },
    onSubmit() {
      let th = this;
      let _item = [];
      let oldMoney = th.residueMoney;
      let isGz = false;
      let reductionType = th.form.reductionType;
      if (typeof reductionType == "object") {
        th.form.reductionType = reductionType.join(",");
      }
      //卡券积分支付等等
      if (th.sourceItem.length > 0) {
        let list = th.sourceItem;
        for (let i = 0; i < list.length; i++) {
          if (list[i].source == 2) {
            isGz = true;
          }
          let arr = {
            billPayId: "",
            billPayCode: "",
            billId: "",
            payMoney: list[i].payMoney,
            source: list[i].source,
            sourceId: "",
            remark: "",
            status: "",
            isDeleted: ""
          };
          arr = Object.assign(arr, list[i]);
          arr.remark = list[i].note;
          _item.push(arr);
          oldMoney = Number(oldMoney - list[i].payMoney).toFixed(2);
        }
      }
      //支付宝等支付方式
      if (th.form.resource == 7) {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.payMoney,
          source: 7,
          sourceId: "",
          remark: th.form.desc,
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.payMoney - oldMoney).toFixed(2);
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.balanceMoney,
          source: 11,
          sourceId: "",
          remark: th.form.desc,
          status: "",
          isDeleted: ""
        });
      } else {
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: th.form.payMoney,
          source: th.form.resource,
          sourceId: "",
          remark: th.form.desc,
          status: "",
          isDeleted: ""
        });
        oldMoney = Number(th.form.payMoney - oldMoney).toFixed(2);
      }
      let j = {
        orderId: th.orderId,
        reductionMoney: th.form.reductionMoney,
        note: th.form.desc,
        reductionType: th.form.reductionType,
        medicalCard: th.form.medicalCard,
        code: th.form.code,
        discountNumber: this.form.discountNumber,
        billPaywaysJson: JSON.stringify(_item)
      };
      if (th.form.reductionMoney != null) {
        j.reductionMoney = th.form.reductionMoney;
        j.note = th.form.desc;
      } else {
        j.reductionMoney = 0;
      }
      if (isGz == false) {
        if (Number(oldMoney) < 0) {
          th.$message.error("支付金额不足！");
          th.showLoading(false);
          return false;
        }
      }
      th.btnLoading = true;
      th.$refs["form"].validate(v => {
        if (v) {
          th.$confirm(`确定收费吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true
          })
            .then(() => {
              th.showLoading(true);
              th.$api
                .payOrder(j)
                .then(res => {
                  if (res.executed) {
                    th.$message.success("支付成功");
                    // th.showLoading(false);
                    th.$router.push({ path: "/page/chargeIndex" });
                    th.showOrder = true;
                    th.btnLoading = false;
                    th.showLoading(false);
                  } else {
                    th.$message.error(res.message);
                    th.btnLoading = false;
                    th.showLoading(false);
                  }
                })
                .catch(error => {
                  th.$message.error(res.message);
                  th.btnLoading = false;
                });
            })
            .catch(error => {
              th.btnLoading = false;
            });
        } else {
          th.btnLoading = false;
        }
      });
    },
    //计算金额
    derate(it) {
      let th = this;
      let money = 0;
      if (it != undefined) {
        if (it.source == 5) {
          if (Number(it.payMoney) > Number(th.detail.patientScore)) {
            th.$message.error("积分不足！！");
            it.payMoney = 0;
            return false;
          }
          if (Number(it.payMoney) > th.jfUse.mostNum) {
            th.$message.warning("单次抵扣积分上限为" + th.jfUse.mostNum);
            return false;
          } else {
            it.payMoney =
              parseInt(it.payMoney / th.jfUse.useNum) * th.jfUse.getNum;
          }
        }
        if (it.source == 6) {
          if (Number(it.payMoney) > Number(th.detail.patientMoney)) {
            th.$message.warning("余额不足！");
            it.payMoney = Number(th.detail.patientMoney);
            return false;
          }
        }
        if (it.payMoney > th.total) {
          th.$message.warning("金额填写有误！");
          it.payMoney = 0;
        }
      } else {
        //计算折扣数
        let _discount =
          (Number(th.form.reductionMoney) / Number(th.total)) * 100;
        if (_discount) {
          th.form.discount = _discount.toFixed(2);
        }
      }
      //减免

      let reductionMoney = th.form.reductionMoney;
      //剩余
      let residueMoney = Number(th.total) - Number(reductionMoney);
      if (reductionMoney != "") {
        // if (Number(reductionMoney) > Number(residueMoney)) {
        //   th.$message.error("减免金额不能大于总金额！");
        //   return false;
        // } else {
        //   residueMoney = Number(th.total) - Number(reductionMoney);
        // }
        if (Number(residueMoney) < 0) {
          th.$message.error("减免金额不能大于总金额！");
          th.form.reductionMoney = th.total;
          return false;
        } else {
          residueMoney = Number(th.total) - Number(reductionMoney);
        }
      }
      //其他付费
      let item = th.sourceItem;
      //计算其他付费时，还需支付价格
      for (let i = 0; i < item.length; i++) {
        if (item[i].payMoney > residueMoney) {
          th.$message.error(item[i].name + "不能大于总金额！");
          break;
        } else {
          residueMoney = Number(residueMoney) - Number(item[i].payMoney);
        }
      }
      if (
        Number.parseFloat(residueMoney) != NaN &&
        Number.parseFloat(residueMoney) != undefined
      ) {
        th.residueMoney = Number(residueMoney).toFixed(2);
      } else {
        th.residueMoney = residueMoney;
      }
      if (
        Number.parseFloat(residueMoney) != NaN &&
        Number.parseFloat(residueMoney) != undefined
      ) {
        th.form.payMoney = Number.parseFloat(residueMoney).toFixed(2);
      }
      //计算找零
      th.getMoney();
    },
    changeSource() {
      let th = this;
      // if (th.form.resource == 14) {
      //   th.$refs["payMoney"].focus();
      // }
      th.form.payMoney = th.residueMoney;
      //找零直接赋值为0
      th.balanceMoney = 0;
    },
    //计算找零
    getMoney() {
      let th = this;
      let zl_Money = 0;
      //reductionMoney  -----------减免价格
      if (th.form.reductionMoney) {
        zl_Money = Number(th.total) - Number(th.form.reductionMoney);
        if (Number(th.form.payMoney)) {
          zl_Money = Number(th.form.payMoney) - Number(zl_Money);
        }
        if (zl_Money != undefined && zl_Money != NaN) {
          th.balanceMoney = 0; // zl_Money.toFixed(2);
        }
      } else {
        //residueMoney ---------剩余支付
        //payMoney ------------  支付方式支付价格
        //balanceMoney -------- 找零价格
        zl_Money = Number(th.form.payMoney) - Number(th.residueMoney);
        if (zl_Money != undefined && zl_Money != NaN) {
          th.balanceMoney = zl_Money.toFixed(2); // zl_Money.toFixed(2);
          // th.form.payMoney = Number(th.balanceMoney);
        }
        if (th.residueMoney) {
          th.form.payMoney = Number.parseFloat(th.residueMoney);
        }
      }
      // th.qxBtns.gz=false;
      // th.qxBtns.kq=false;
      // th.qxBtns.ye=false;
      // th.qxBtns.jf=false;
      // th.qxBtns.jm=false;
      // th.isChecked=true
    },
    //获取小程序验证码
    getSmallCode() {
      let th = this;
      th.$api.createSmallAppCode({ medicalCard: th.medicalCard }).then(res => {
        if (res.executed) {
          th.form.medicalCard = th.medicalCard;
          th.form.payMoney = th.residueMoney;
          th.medicalCard = th.residueMoney;
          th.textType = "text";
          th.smallDisabled = true;
        } else {
          th.$message.error(res.message);
        }
      });
    },
    //是否折扣
    changeDiscount() {
      if (!this.isDiscount) {
        this.residueMoney = Number(
          this.totalMoney - this.form.reductionMoney
        ).toFixed(2);
        this.form.payMoney = Number(
          this.totalMoney - this.form.reductionMoney
        ).toFixed(2);
        this.total = Number(this.totalMoney - this.form.reductionMoney).toFixed(
          2
        );
        this.form.discountNumber = "";
      }
    },
    //计算折扣金额
    computeDiscount() {
      this.residueMoney = Number(
        this.totalMoney * this.form.discountNumber - this.form.reductionMoney
      ).toFixed(2);
      this.form.payMoney = Number(
        this.totalMoney * this.form.discountNumber - this.form.reductionMoney
      ).toFixed(2);
      this.total = Number(
        this.totalMoney * this.form.discountNumber - this.form.reductionMoney
      ).toFixed(2);
      // this.form.reductionMoney = Number(
      //   this.totalMoney * this.form.discountNumber - this.form.reductionMoney
      // ).toFixed(2);
    }
  },
  components: {
    pay: () => import("./_child/otherPay")
  }
};
</script>
<style lang="scss" scoped>
@import "./_css/pay.scss";
.pay_content {
  &::after {
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
    overflow: hidden;
    content: ".";
  }
  .el-radio {
    width: 120px;
    margin: 0;
    padding: 0;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .el-page-header {
    margin-bottom: 20px;
  }
}
.main_left {
  width: 250px;
  float: left;
  position: relative;
  margin-right: -250px;
}
.main_right {
  width: 100%;
  float: right;
  .main_right_c {
    margin-left: 270px;
  }
}
.pay_left {
  padding: 20px;
  background: #40a48b;
  color: #fff;
  .pay_left_item {
    margin-bottom: 30px;
    line-height: 1.5;
  }
  .pay_left_item.pay_left_mb {
    margin-bottom: 80px;
  }
  .pay_total {
    font-size: 30px;
    color: #f9ed54;
  }
}
.el-checkbox-group .el-checkbox {
  width: 120px;
  float: left;
  margin: 0;
  padding: 0;
}
.needPay {
  font-size: 18px;
  font-weight: bold;
  color: #ff5b5b;
}
.danger {
  color: #ff5b5b;
}
.el-form-item__content .el-input-group {
  margin-bottom: 15px;
}
.ml20 {
  margin-left: 20px;
}
</style>